"use client";

import React, { useRef, useState } from "react";
import {
  Box,
  Button,
  Typography,
  Paper,
  LinearProgress,
  Alert,
  IconButton,
  Tooltip,
} from "@mui/material";
import {
  CloudUpload as UploadIcon,
  Description as DocumentIcon,
  Close as CloseIcon,
  CheckCircle as SuccessIcon,
} from "@mui/icons-material";

interface DocumentUploadProps {
  onFileSelect: (file: File) => void;
  onRemove: () => void;
  onClose?: () => void; // 新增关闭面板的回调
  selectedFile: File | null;
  isUploading?: boolean;
  error?: string | null;
}

export default function DocumentUpload({
  onFileSelect,
  onRemove,
  onClose,
  selectedFile,
  isUploading = false,
  error = null,
}: DocumentUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [dragActive, setDragActive] = useState(false);

  // 处理文件选择
  const handleFileSelect = (file: File) => {
    // 检查文件类型
    if (!file.name.toLowerCase().endsWith(".docx")) {
      alert("请选择.docx格式的Word文档");
      return;
    }

    // 检查文件大小（10MB限制）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      alert("文件大小不能超过10MB");
      return;
    }

    onFileSelect(file);
  };

  // 处理拖拽
  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileSelect(e.dataTransfer.files[0]);
    }
  };

  // 处理点击上传
  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0]);
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  return (
    <Box sx={{ mb: 2, position: "relative" }}>
      {/* 关闭按钮 */}
      {onClose && (
        <Box sx={{ display: "flex", justifyContent: "flex-end", mb: 1 }}>
          <Tooltip title="关闭上传面板">
            <IconButton
              size="small"
              onClick={onClose}
              sx={{
                color: "text.secondary",
                "&:hover": {
                  color: "text.primary",
                  bgcolor: "action.hover",
                },
              }}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      )}

      {/* 文件上传区域 */}
      {!selectedFile && (
        <Paper
          elevation={1}
          sx={{
            p: 3,
            textAlign: "center",
            border: "2px dashed",
            borderColor: dragActive ? "primary.main" : "grey.300",
            bgcolor: dragActive ? "primary.50" : "background.paper",
            cursor: "pointer",
            transition: "all 0.2s ease-in-out",
            "&:hover": {
              borderColor: "primary.main",
              bgcolor: "primary.50",
            },
          }}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
          onClick={handleClick}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".docx"
            onChange={handleFileInputChange}
            style={{ display: "none" }}
          />

          <UploadIcon
            sx={{
              fontSize: 48,
              color: "primary.main",
              mb: 2,
            }}
          />

          <Typography variant="h6" gutterBottom>
            上传Word文档
          </Typography>

          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            支持.docx格式，最大10MB
          </Typography>

          <Button
            variant="contained"
            startIcon={<UploadIcon />}
            disabled={isUploading}
          >
            选择文件
          </Button>

          <Typography variant="caption" display="block" sx={{ mt: 1 }}>
            或直接拖拽文件到此区域
          </Typography>
        </Paper>
      )}

      {/* 已选择的文件 */}
      {selectedFile && (
        <Paper
          elevation={1}
          sx={{
            p: 2,
            display: "flex",
            alignItems: "center",
            gap: 2,
            bgcolor: "success.50",
            border: "1px solid",
            borderColor: "success.200",
          }}
        >
          <SuccessIcon color="success" />

          <Box sx={{ flexGrow: 1 }}>
            <Typography
              variant="subtitle2"
              sx={{ display: "flex", alignItems: "center", gap: 1 }}
            >
              <DocumentIcon fontSize="small" />
              {selectedFile.name}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {formatFileSize(selectedFile.size)}
            </Typography>
          </Box>

          <Tooltip title="移除文件">
            <IconButton size="small" onClick={onRemove} disabled={isUploading}>
              <CloseIcon />
            </IconButton>
          </Tooltip>
        </Paper>
      )}

      {/* 上传进度 */}
      {isUploading && (
        <Box sx={{ mt: 1 }}>
          <Typography variant="caption" color="text.secondary">
            正在解析Word文档内容...
          </Typography>
          <LinearProgress sx={{ mt: 1 }} />
        </Box>
      )}

      {/* 错误提示 */}
      {error && (
        <Alert severity="error" sx={{ mt: 1 }}>
          {error}
        </Alert>
      )}
    </Box>
  );
}
